package org.jeecg.modules.course.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SimpleQuery;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.course.entity.GwCourseCatalog;
import org.jeecg.modules.course.service.IGwCourseCatalogService;

import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 课程目录
 * @Author: jeecg-boot
 * @Date: 2024-09-30
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "课程目录")
@RestController
@RequestMapping("/course/gwCourseCatalog")
public class GwCourseCatalogController extends JeecgController<GwCourseCatalog, IGwCourseCatalogService> {

    @Resource
    private IGwCourseCatalogService gwCourseCatalogService;

    /**
     * 分页列表查询
     *
     * @param gwCourseCatalog
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "课程目录-分页列表查询")
    @ApiOperation(value = "课程目录-分页列表查询", notes = "课程目录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GwCourseCatalog gwCourseCatalog,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<GwCourseCatalog> queryWrapper = QueryGenerator.initQueryWrapper(gwCourseCatalog, req.getParameterMap());
        Page<GwCourseCatalog> page = new Page<GwCourseCatalog>(pageNo, pageSize);
        IPage<GwCourseCatalog> pageList = gwCourseCatalogService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param gwCourseCatalog
     * @return
     */
    @AutoLog(value = "课程目录-添加")
    @ApiOperation(value = "课程目录-添加", notes = "课程目录-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GwCourseCatalog gwCourseCatalog) {
        gwCourseCatalogService.save(gwCourseCatalog);
        return Result.OK("添加成功！", gwCourseCatalog.getId());
    }

    /**
     * 编辑
     *
     * @param gwCourseCatalog
     * @return
     */
    @AutoLog(value = "课程目录-编辑")
    @ApiOperation(value = "课程目录-编辑", notes = "课程目录-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody GwCourseCatalog gwCourseCatalog) {
        gwCourseCatalogService.updateById(gwCourseCatalog);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "课程目录-通过id删除")
    @ApiOperation(value = "课程目录-通过id删除", notes = "课程目录-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        gwCourseCatalogService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "课程目录-批量删除")
    @ApiOperation(value = "课程目录-批量删除", notes = "课程目录-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.gwCourseCatalogService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "课程目录-通过id查询")
    @ApiOperation(value = "课程目录-通过id查询", notes = "课程目录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GwCourseCatalog gwCourseCatalog = gwCourseCatalogService.getById(id);
        return Result.OK(gwCourseCatalog);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param gwCourseCatalog
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GwCourseCatalog gwCourseCatalog) {
        return super.exportXls(request, gwCourseCatalog, GwCourseCatalog.class, "课程目录");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GwCourseCatalog.class);
    }

    /**
     * 通过id查询目录列表
     *
     * @param id 课程标识
     * @return 目录结构
     */
    @ApiOperation(value = "课程目录列表-通过id查询", notes = "课程目录-通过id查询")
    @GetMapping(value = "/catalogById")
    public Result<List<CourseCatalogResult>> catalogByIdGet(@RequestParam(name = "id", required = true) String id) {

        LambdaQueryWrapper<GwCourseCatalog> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GwCourseCatalog::getCourseId, id);
        final List<GwCourseCatalog> list = gwCourseCatalogService.list(lambdaQueryWrapper);
        List<CourseCatalogResult> items = list.stream().map(item -> {
            CourseCatalogResult catalog = new CourseCatalogResult();
            catalog.setId(item.getId());
            catalog.setCatalogName(item.getCatalogName());
            catalog.setParentId(item.getParentId());
            catalog.setSort(item.getSort());
            return catalog;
        }).collect(Collectors.toList());
        items = buildTree(items);
        return Result.OK(items);
    }

    /**
     * 保存课程目录
     *
     * @param params 课程目录 参数
     * @return 执行结果
     */
    @ApiOperation(value = "保存课程目录", notes = "保存课程目录")
    @PostMapping(value = "/catalogById/{id}")
    public Result<Void> catalogByIdPost(@PathVariable String id, @Valid @RequestBody List<CourseCatalogResult> params) {

        // 处理所有的目录数据
        save(id, params);

        return Result.OK(null);
    }

    private void saveQuestionBatch(String courseId, List<CourseQuestionResult> params) {

        for (int i = 0; i < params.size(); i++) {
            CourseQuestionResult param = params.get(i);
            // 保存所有的目录
            GwCourseCatalog entity = new GwCourseCatalog();
            BeanUtils.copyProperties(param, entity);
            entity.setCourseId(courseId);
            entity.setSort(i);
            this.gwCourseCatalogService.save(entity);

            // 保存子目录
            if (param.getChildren() != null && !param.getChildren().isEmpty()) {
                for (CourseCatalogResult child : param.getChildren()) {
                    child.setParentId(entity.getId());
                }
                // this.save(courseId, param.getChildren());
            }
        }
    }



    private void save(String courseId, List<CourseCatalogResult> params) {

        for (int i = 0; i < params.size(); i++) {
            CourseCatalogResult param = params.get(i);
            // 保存所有的目录
            GwCourseCatalog entity = new GwCourseCatalog();
            BeanUtils.copyProperties(param, entity);
            entity.setCourseId(courseId);
            entity.setSort(i);
            this.gwCourseCatalogService.save(entity);

            // 保存子目录
            if (param.getChildren() != null && !param.getChildren().isEmpty()) {
                for (CourseCatalogResult child : param.getChildren()) {
                    child.setParentId(entity.getId());
                }
                this.save(courseId, param.getChildren());
            }
        }
    }

    @Data
    private static class CourseCatalogResult {

        @ApiModelProperty(value = "目录标识")
        private String id;

        @ApiModelProperty(value = "目录名称")
        private String catalogName;

        @ApiModelProperty(value = "排序")
        private Integer sort;

        @ApiModelProperty(value = "父级目录标识")
        private String parentId;

        @ApiModelProperty(value = "课件URL（逗号分隔）")
        private java.lang.String coursewareUrl;

        @ApiModelProperty(value = "视频URL（逗号分隔）")
        private java.lang.String videoUrl;

        @ApiModelProperty(value = "音频URL（逗号分隔）")
        private java.lang.Integer audioUrl;

        @ApiModelProperty(value = "下级目录列表")
        private List<CourseCatalogResult> children;
    }


    @Data
    private static class CourseQuestionResult {

        @ApiModelProperty(value = "问题标识")
        private String id;

        @ApiModelProperty(value = "问题")
        private String question;

        @ApiModelProperty(value = "问题类型：单选/多选")
        private Integer questionType;

        @ApiModelProperty(value = "父级目录标识")
        private String parentId;

        @ApiModelProperty(value = "课件URL（逗号分隔）")
        private java.lang.String coursewareUrl;

        @ApiModelProperty(value = "视频URL（逗号分隔）")
        private java.lang.String videoUrl;

        @ApiModelProperty(value = "音频URL（逗号分隔）")
        private java.lang.Integer audioUrl;

        @ApiModelProperty(value = "下级目录列表")
        private List<CourseCatalogResult> children;
    }

    public static List<CourseCatalogResult> buildTree(List<CourseCatalogResult> items) {
        // 创建一个根节点的列表
        List<CourseCatalogResult> tree = new ArrayList<>();

        // 创建一个映射，以便快速查找每个目录
        Map<String, CourseCatalogResult> catalogMap = items.stream()
                .collect(Collectors.toMap(CourseCatalogResult::getId, item -> item));

        items = items.stream().sorted((o1, o2) -> {
            if (o1.getParentId().equals(o2.getParentId())) {
                return o1.getSort().compareTo(o2.getSort());
            } else {
                return o1.getParentId().compareTo(o2.getParentId());
            }
        }).collect(Collectors.toList());
        // 构建树状结构
        for (CourseCatalogResult item : items) {
            if (item.getParentId() == null || "".equals(item.getParentId()) || "0".equals(item.getParentId())) {
                // 如果没有父级，则是根节点
                tree.add(item);
            } else {
                // 否则，找到父级并将当前目录添加到其子目录中
                CourseCatalogResult parent = catalogMap.get(item.getParentId());
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(item);
                }
            }
        }

        return tree;
    }



    /**
     * 保存课程测试问题
     *
     * @param params 课程问题参数
     * @return 执行结果
     */
    @ApiOperation(value = "保存课程测试问题")
    @PostMapping(value = "/question/save/{id}")
    public Result<Void> questionSaveBatch(@PathVariable String id, @Valid @RequestBody List<CourseQuestionResult> params) {

        // 处理所有的目录数据
        saveQuestionBatch(id, params);

        return Result.OK(null);
    }

}
